import { NestFactory } from "@nestjs/core";
import { BreathServerModule } from "./breath-server.module";
import { WsAdapter } from "@nestjs/platform-ws";
import { LogService } from "@app/log";
import { initConfig } from "../config";
import { configuration } from "../../../config/config";
import { MicroserviceOptions, Transport } from "@nestjs/microservices";

async function bootstrap() {
  if (configuration.breathServer.userVersion === 1) {
    const app = await NestFactory.create(BreathServerModule, {
      bufferLogs: true,
    });
    app.enableCors();
    const logger = app.get(LogService);
    app.useLogger(logger);
    app.useWebSocketAdapter(new WsAdapter(app));
    await app.listen(9094);
  } else {
    const app = await NestFactory.create(BreathServerModule, {
      bufferLogs: true,
    });
    app.enableCors();
    await Promise.all([
      app.listen(configuration.breathServer.http_port), // 启动 HTTP 服务
      app.connectMicroservice<MicroserviceOptions>({
        transport: Transport.NATS,
        options: {
          servers: configuration.natsServer,
        },
      }),
    ]);
    // 启动所有微服务
    await app.startAllMicroservices();
    console.log(
      "breathServer is running on http port " +
        configuration.breathServer.http_port,
      "NATS client start",
    );
  }
}

initConfig().then(() => {
  bootstrap();
});
